<?php
// +----------------------------------------------------------------------
// | 小说系统 [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------

namespace app\common\controller;
use app\common\model\AuthGroup;
use app\common\model\AuthRule;

class Qapp extends Base {

	
	public function _initialize() {
		parent::_initialize();
		
		if (!is_login() and !in_array($this->url, array('qapp/index/login', 'qapp/index/logout', 'qapp/index/verify'))) {
			$this->redirect('qapp/index/login');
		}

		if (!in_array($this->url, array('qapp/index/login', 'qapp/index/logout', 'qapp/index/verify'))) {

			// 是否是超级管理员
			define('IS_ROOT', is_administrator());
			if (!IS_ROOT && \think\Config::get('admin_allow_ip')) {
				// 检查IP地址访问
				if (!in_array(get_client_ip(), explode(',', \think\Config::get('admin_allow_ip')))) {
					$this->error('403:禁止访问');
				}
			}

			// 检测系统权限
			if (!IS_ROOT) {
				$access = $this->accessControl();
				if (false === $access) {
					$this->error('403:禁止访问');
				} elseif (null === $access) {
					$dynamic = $this->checkDynamic(); //检测分类栏目有关的各项动态权限
					
					if ($dynamic === false) {
						//检测访问权限
						if (!$this->checkRule($this->url, array('in', '1,2'))) {
							$this->error('未授权访问!');
						}/*** else {
							// 检测分类及内容有关的各项动态权限
							$dynamic = $this->checkDynamic();
							if (false === $dynamic) {
								$this->error('未授权访问!');
							}
						}
						****/
					}/*** elseif ($dynamic === false) {
						$this->error('未授权访问!');
					}***/
				}
			}
			
			//菜单设置
			$this->setMenu();			
			$this->setMeta();
		}
	}
	
	/**
	 * 权限检测
	 * @param string  $rule    检测的规则
	 * @param string  $mode    check模式
	 * @return boolean
	 * @author 朱亚杰  <xcoolcc@gmail.com>
	 */
	final protected function checkRule($rule, $type = AuthRule::rule_url, $mode = 'url') {
		static $Auth = null;
		if (!$Auth) {
			$Auth = new \com\Auth();
		}
		if (!$Auth->check($rule, session('user_auth.uid'), $type, $mode)) {
			return false;
		}
		return true;
	}

	/**
	 * 检测是否是需要动态判断的权限
	 * @return boolean|null
	 *      返回true则表示当前访问有权限
	 *      返回false则表示当前访问无权限
	 *      返回null，则表示权限不明
	 *
	 * @author 朱亚杰  <xcoolcc@gmail.com>
	 */
	protected function checkDynamic() {
		if (IS_ROOT) {
			return true; //管理员允许访问任何页面
		}
		return null; //不明,需checkRule
	}

	/**
	 * action访问控制,在 **登陆成功** 后执行的第一项权限检测任务
	 *
	 * @return boolean|null  返回值必须使用 `===` 进行判断
	 *
	 *   返回 **false**, 不允许任何人访问(超管除外)
	 *   返回 **true**, 允许任何管理员访问,无需执行节点权限检测
	 *   返回 **null**, 需要继续执行节点权限检测决定是否允许访问
	 * @author 朱亚杰  <xcoolcc@gmail.com>
	 */
	final protected function accessControl() {
		$allow = \think\Config::get('allow_visit');
		$deny  = \think\Config::get('deny_visit');
		$check = strtolower($this->request->controller() . '/' . $this->request->action());
		if (!empty($deny) && in_array_case($check, $deny)) {
			return false; //非超管禁止访问deny中的方法
		}
		if (!empty($allow) && in_array_case($check, $allow)) {
			return true;
		}
		return null; //需要检测节点权限
	}
	
	protected function setMenu() {
		$category    =   array();
		
		$controller = $this->url;
		$where['pid']  = 0;
		$where['hide'] = 0;
		$where['type'] = 'admin';
		if (!config('develop_mode')) {
			// 是否开发者模式
			$where['is_dev'] = 0;
		}
		$category = db('menu')->field('id,title,url,icon,"" as style')->where($where)->order('sort asc')->select();
		
		foreach ($category as $key => $value) {
			//此处用来做权限判断
			if (!empty($value['url'])&&!IS_ROOT && !$this->checkRule($value['url'], 2, null)) {
				unset($category[$key]);
				continue; //继续循环
			}
			
		}
		//var_dump($category);exit();
		
		foreach ($category as $k => $v ) { 
				//一级分类是否当前
				
				if (strpos($v['url'],$controller) !==false) {
					$category [$k]['style'] = "active";
				}
				
			 //获取二级分类的合法url
				$where          =   array();
				$where['pid']   =   $v['id'];
				$where['hide']  =   0;
				if(!config('develop_mode')){ // 是否开发者模式
					$where['is_dev']    =   0;
				}
				$second_urls = db('Menu')->where($where)->field('id,pid,title,url,icon,tip')->order('sort')->select();
				
				
				// 检测菜单权限
				$to_check_urls = array();
				foreach ($second_urls as $key=>$value) {
					
					if ($controller == $value['url']) {
						
						$second_urls[$key]['style'] = "active";
						//$menu['child'][$value['group']]['style']= "open";
						
					}else{
						
						$pid = db('Menu')->where(['url'=>$controller,'hide'=>0])->where('group','')->value('pid');
						if($pid){
							$third_url = db('Menu')->where(['id'=>$pid,'hide'=>0])->value('url');
							if($third_url == $value['url']){
								$second_urls[$key]['style'] = "active";
							}else{
								$second_urls[$key]['style'] = "";
							}
						}else{
							$second_urls[$key]['style'] = "";
						}

					}
					if (!IS_ROOT && !$this->checkRule($value['url'], 2, null)) {
						unset($second_urls[$key]);
						continue; //继续循环
					}
				}

				if($second_urls){
					$category [$k]['doc'] = $second_urls;
				}else{
					if($k!=0 && empty($v['url'])){
						unset($category[$k]);
					}
				}
				
				
				/*
				$group_map['group']=array('neq','');
				$group_map['pid']=$v['id'];
				if(!IS_ROOT){
					$group_map['url']=array('in',$to_check_urls);
				}
				$groups[$k] = db('Menu')->where($group_map)->distinct(true)->order('sort')->column("group");
				
					
				// 按照分组生成子菜单树					
				foreach ($groups[$k] as $g) {
					$map = array('group'=>$g);
					if(isset($to_check_urls)){
						if(empty($to_check_urls)){
							// 没有任何权限
							continue;
						}else{
							$map['url'] = array('in', $to_check_urls);
						}
					}
					$map['pid']     =   $v['id'];
					$map['hide']    =   0;
					if(!config('develop_mode')){ // 是否开发者模式
						$map['is_dev']  =   0;
					}
					$cateList = db('Menu')->where($map)->field('id,pid,title,url,tip')->order('sort')->select();	var_dump($cateList);
					exit();
					$category [$k]['doc'][] =$cateList;
					//$category [$k]['doc'][] = list_to_tree($cateList, 'id', 'pid', 'operater', $v['id']);
					
				}
				*/
			
		}
		//var_dump($category);
		$this->assign('__menu__', $category);
	}
	
	protected function getContentMenu() {
		$model = \think\Loader::model('Model');
		$list  = array();
		$map   = array(
			'status' => array('gt', 0)
		);
		$list = $model::where($map)->field("name,id,title,icon,'' as 'style'")->select();

		//判断是否有模型权限
		$models = AuthGroup::getAuthModels(session('user_auth.uid'));
		foreach ($list as $key => $value) {
			if (IS_ROOT || in_array($value['id'], $models)) {
				if ('admin/content/index' == $this->url && input('model_id') == $value['id']) {
					$value['style'] = "active";
				}
				$value['url']   = "admin/content/index?model_id=" . $value['id'];
				$value['title'] = $value['title'] . "管理";
				$value['icon']  = $value['icon'] ? $value['icon'] : 'file';
				$menu[]         = $value;
			}
		}
		
		/**
		if (!empty($menu)) {
			$this->assign('extend_menu', array('小说管理' => $menu));
		}
		***/
	}

	/****导出excel*****/
	public function xlsout($filename='数据表',$headArr,$list){
		ini_set('memory_limit','2560M');
		//导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
		import("PHPExcel.PHPExcel", EXTEND_PATH);
		import("PHPExcel.PHPExcel.Writer.Excel2007", EXTEND_PATH);
		import("PHPExcel.PHPExcel.IOFactory.php", EXTEND_PATH);
		$this->getExcel($filename,$headArr,$list);
	}

	public	function getExcel($fileName,$headArr,$data){
        //对数据进行检验
        if(empty($data) || !is_array($data)){
            header("content-type:text/html;charset=utf-8");
            die("导出内容不能为空！");
        }
        //检查文件名
        if(empty($fileName)){
            exit;
        }

        $date = date("Y_m_d",time());
        $fileName .= "_{$date}.xlsx";
        
        $cacheMethod = \PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
        $cacheSettings = array('memoryCacheSize'=>'2048MB','cacheTime' => 600);         \PHPExcel_Settings::setCacheStorageMethod($cacheMethod, $cacheSettings);


        //创建PHPExcel对象，注意，不能少了\
        $objPHPExcel = new \PHPExcel();
        $objProps = $objPHPExcel->getProperties();

      
		//设置表头
		$key = 0;
		foreach($headArr as $v){
			//注意，不能少了。将列数字转换为字母\
			$colum = \PHPExcel_Cell::stringFromColumnIndex($key);
			$objPHPExcel->setActiveSheetIndex(0) ->setCellValue($colum.'1', $v);
			$key += 1;
		}
		$column = 2;
		$objActSheet = $objPHPExcel->getActiveSheet();

		//设置为文本格式
		foreach($data as $key => $rows){ //行写入
			$span = 0;
			foreach($rows as $keyName=>$value){// 列写入
				$j = \PHPExcel_Cell::stringFromColumnIndex($span);
				if (preg_match('/^([12]\d\d\d)-(0[1-9]|1[0-2])-(3[01]|[12]\d|0[1-9]) ([0-5]\d):([0-5]\d):([0-5]\d)$/', $value)) {//修改单元格为时间格式
					$value = strtotime($value);
					$objActSheet->setCellValue($j.$column, \PHPExcel_Shared_Date::PHPToExcel($value));
					$objActSheet->getStyle($j.$column)->getNumberFormat()->setFormatCode(\PHPExcel_Style_NumberFormat::FORMAT_DATE_XLSX22);
				}else{
					//$objActSheet->setCellValue($j.$column, $value);
					//显式指定内容类型
					$objActSheet->setCellValueExplicit($j.$column, $value, \PHPExcel_Cell_DataType::TYPE_STRING);

				}
				//$objActSheet->setCellValue($j.$column, $value);
				$span++;
			}
			$column++;
		}
       

        $fileName = iconv("utf-8", "gb2312", $fileName);
        //重命名表
        // $objPHPExcel->getActiveSheet()->setTitle('test');
        //设置活动单指数到第一个表,所以Excel打开这是第一个表
        $objPHPExcel->setActiveSheetIndex(0);
        ob_end_clean();//清除缓冲区,避免乱码
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');

        $objWriter = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save('php://output'); //文件通过浏览器下载

        exit;
	}
}
